package cn.rkylin.oms.aftersale.event.controller;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.aftersale.event.dao.IAfterSaleEventDAO;
import cn.rkylin.oms.aftersale.event.service.IAfterSaleEventService;
import cn.rkylin.oms.aftersale.event.vo.AfterSaleEventVO;
import cn.rkylin.oms.common.annotation.SystemControllerLog;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.system.dictionary.domain.OMS_DICT;
import cn.rkylin.oms.system.dictionary.service.IDictService;
import cn.rkylin.oms.system.user.service.IUserService;
import cn.rkylin.oms.system.user.vo.UserVO;

/**
 * 类名:AfterSaleEventController <br/>
 * 作用: 售后事件控制器. <br/>
 * 创建原因: 售后事件控制器. <br/>
 * 创建时间: 2017年9月26日 下午2:16:49 <br/>
 *
 * @author zhanghao
 * @version v1.0
 */
@Controller
@RequestMapping("afterSale")
public class AfterSaleEventController extends ApolloController {
    /**
     * eventService:售后事件服务层.
     */
    @Autowired
    private IAfterSaleEventService eventService;

    /**
     * 用户业务服务对象
     */
    @Autowired
    private IUserService userService;

    /**
     * 参数服务层
     */
    @Autowired
    private IDictService dictService;

    private static final Log logger = LogFactory.getLog(AfterSaleEventController.class);

    /**
     * getEventList:根据查询条件获取查询售后事件的列表. <br/>
     * 
     * @param quickSearch
     * @param start
     * @param length
     * @param formJson
     * @param eventStatus
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getEventList")
    public Map<String, Object> getEventList(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
            @RequestParam(required = false, defaultValue = "10") int length, String formJson, String eventStatus) throws Exception {
        logger.info("查询售后事件：/afterSale/getEventList");

        AfterSaleEventVO queryParamVO = new AfterSaleEventVO();
        // 设置售后事件状态
        queryParamVO.setEventStatus(eventStatus);
        // 获取当前登录人
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null) {
            return getFailedMap("查询当前登录人失败");
        }
        // 获取当前登录人所属项目
        String projectId = currentUser.getCurrentProject().getPrjId();
        if (StringUtils.isBlank(projectId)) {
            return getFailedMap("查询当前登录人所属项目失败");
        }
        // 设置项目id
        queryParamVO.setPrjId(projectId);
        // 快速查询
        if (quickSearch != null && StringUtils.isNotEmpty(quickSearch)) {
            quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
            if (StringUtils.isNotEmpty(quickSearch)) {
                queryParamVO.setQuickSearch(quickSearch.trim());
            }
        }
        // 高级查询
        if (formJson != null && StringUtils.isNotEmpty(formJson)) {
            formJson = URLDecoder.decode(formJson, "UTF-8");
            Map<String, String> mapItem = JSONObject.parseObject(formJson, Map.class);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            if (mapItem != null && !mapItem.isEmpty()) {
                // 实际处理人
                if (StringUtils.isNotEmpty(mapItem.get("queryFactDealUser"))) {
                    queryParamVO.setQueryFactDealUser(mapItem.get("queryFactDealUser"));
                }
                // 创建人
                if (StringUtils.isNotEmpty(mapItem.get("queryEventCreator"))) {
                    queryParamVO.setQueryEventCreator(mapItem.get("queryEventCreator"));
                }
                // 售后事件类型
                if (StringUtils.isNotEmpty(mapItem.get("queryEventType"))) {
                    queryParamVO.setQueryEventType(mapItem.get("queryEventType"));
                }
                // 日期类型
                if (StringUtils.isNotEmpty(mapItem.get("queryDateType"))) {
                    queryParamVO.setQueryDateType(mapItem.get("queryDateType"));
                }
                // 开始日期
                if (StringUtils.isNotEmpty(mapItem.get("queryDateStart"))) {
                    queryParamVO.setQueryDateStart(sdf.parse(mapItem.get("queryDateStart")));
                }
                // 结束日期
                if (StringUtils.isNotEmpty(mapItem.get("queryDateEnd"))) {
                    queryParamVO.setQueryDateEnd(sdf.parse(mapItem.get("queryDateEnd")));
                }
            }

        }

        Map<String, String> replaceFieldsMap = new HashMap<String, String>();
        // 排序语句生成
        String orderStatement = getOrderString(IAfterSaleEventDAO.class.getName(), "pageSelectEventByCondition", replaceFieldsMap);
        if (StringUtils.isNotEmpty(orderStatement)) {
            queryParamVO.setOrderBy(orderStatement);
        }
        // 处理分页信息
        if (length == -1) {
            length = Integer.MAX_VALUE;
        }
        int page = start / length + 1;

        // 执行查询
        PageInfo<AfterSaleEventVO> eventVOList = eventService.queryEventList(page, length, queryParamVO);

        // 列表中最后项，下拉按钮往上翻
        if (eventVOList != null && eventVOList.getList().size() > 3) {
            eventVOList.getList().get(eventVOList.getList().size() - 1).setReversePosition("dropup");
            if (eventVOList.getList().size() > 4) {
                eventVOList.getList().get(eventVOList.getList().size() - 2).setReversePosition("dropup");
            }
        }

        Map<String, Object> returnMap = new HashMap<>();
        if (null != eventVOList) {
            // 将数据库存储的事件类型key转换为value
            OMS_DICT dict = new OMS_DICT();
            dict.setDictCode("AFTER_SALE_TYPE");
            List list = dictService.getParamDictByCode(dict);
            for (int i = 0; i < eventVOList.getList().size(); i++) {
                eventVOList.getList().get(i).setEventType(list.get(Integer.parseInt(eventVOList.getList().get(i).getEventType())).toString());
            }

            // 将数据库存储的创建人id转换为fullname
            for (int i = 0; i < eventVOList.getList().size(); i++) {
                UserVO param = new UserVO();
                param.setUserId(eventVOList.getList().get(i).getEventCreator());
                PageInfo<UserVO> userVOList = userService.findByWhere(1, Integer.MAX_VALUE, param, true, false, true, false);
                eventVOList.getList().get(i).setEventCreator(userVOList.getList().get(0).getUserFullname());
            }

            returnMap = getSuccessMap("查询售后事件表单数据成功");
            returnMap.put(RECORDS_FILTERED, eventVOList.getTotal());
            returnMap.put(RECORDS_TOTAL, eventVOList.getTotal());
            returnMap.put(RETURN_DATA, eventVOList.getList());
        } else {
            returnMap = getFailedMap("查询售后事件表单数据失败");
        }
        logger.info("查询售后事件表单数据调用结束");
        return returnMap;
    }

    /**
     * queryStateCount:事件的各种count
     * 
     * @param quickSearch
     * @param formJson
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryStateCount")
    public Map<String, Object> queryStateCount(String quickSearch, String formJson) {
        logger.info("查询售后事件状态数据：/afterSale/queryStateCount");
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            AfterSaleEventVO queryParamVO = new AfterSaleEventVO();
            // 获取当前登录人
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            if (currentUser == null) {
                return getFailedMap("查询当前登录人失败");
            }
            // 获取当前登录人所属项目
            String projectId = currentUser.getCurrentProject().getPrjId();
            if (StringUtils.isBlank(projectId)) {
                return getFailedMap("查询当前登录人所属项目失败");
            }
            // 设置项目id
            queryParamVO.setPrjId(projectId);
            // 快速查询
            if (quickSearch != null && StringUtils.isNotEmpty(quickSearch)) {
                quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
                if (StringUtils.isNotEmpty(quickSearch)) {
                    queryParamVO.setQuickSearch(quickSearch);
                }
            }
            // 高级查询
            if (formJson != null && StringUtils.isNotEmpty(formJson)) {
                formJson = URLDecoder.decode(formJson, "UTF-8");
                Map<String, String> mapItem = JSONObject.parseObject(formJson, Map.class);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                if (mapItem != null && !mapItem.isEmpty()) {
                    // 实际处理人
                    if (StringUtils.isNotEmpty(mapItem.get("queryFactDealUser"))) {
                        queryParamVO.setQueryFactDealUser(mapItem.get("queryFactDealUser"));
                    }
                    // 创建人
                    if (StringUtils.isNotEmpty(mapItem.get("queryEventCreator"))) {
                        queryParamVO.setQueryEventCreator(mapItem.get("queryEventCreator"));
                    }
                    // 售后事件类型
                    if (StringUtils.isNotEmpty(mapItem.get("queryEventType"))) {
                        queryParamVO.setEventType(mapItem.get("queryEventType"));
                    }
                    // 日期类型
                    if (StringUtils.isNotEmpty(mapItem.get("queryDateType"))) {
                        queryParamVO.setQueryDateType(mapItem.get("queryDateType"));
                    }
                    // 开始日期
                    if (StringUtils.isNotEmpty(mapItem.get("queryDateStart"))) {
                        queryParamVO.setQueryDateStart(sdf.parse(mapItem.get("queryDateStart")));
                    }
                    // 结束日期
                    if (StringUtils.isNotEmpty(mapItem.get("queryDateEnd"))) {
                        queryParamVO.setQueryDateEnd(sdf.parse(mapItem.get("queryDateEnd")));
                    }
                }

            }
            // 执行查询
            List<AfterSaleEventVO> list = eventService.findCounts(queryParamVO);
            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            int countPending = 0;
            int countProcessing = 0;
            int countComplete = 0;
            if (list != null && list.size() > 0) {
                countPending = list.get(0).getCountPending() != null ? list.get(0).getCountPending().intValue() : 0;
                countProcessing = list.get(0).getCountProcessing() != null ? list.get(0).getCountProcessing().intValue() : 0;
                countComplete = list.get(0).getCountComplete() != null ? list.get(0).getCountComplete().intValue() : 0;
            }
            returnMap.put("countPending", countPending);
            returnMap.put("countProcessing", countProcessing);
            returnMap.put("countComplete", countComplete);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;

    }

    /**
     * 根据补发id获取补发单
     * 
     * @param resendId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getEvent")
    public Map<String, Object> getEvent(@RequestParam(value = "eventId") String eventId) {
        logger.info(String.format("获取售后事件：/afterSale/getEvent/%s", eventId));
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            AfterSaleEventVO result = eventService.queryEventById(eventId);
            if (null != result) {
                returnMap = getSuccessMap("系统调用完成");
                returnMap.put(RETURN_DATA, result);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap(e.getMessage());
        }
        return returnMap;
    }

    /**
     * saveEvent:保存售后事件
     * 
     * @param eventVO
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/saveEvent")
    @SystemControllerLog(module = "售后事件管理", operation = "保存售后事件", keyCode = "eventId")
    public Map<String, Object> saveEvent(@RequestBody AfterSaleEventVO eventVO) {
        logger.info("保存售后事件：/afterSale/saveEvent");
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            String returnMsg = eventService.saveEvent(eventVO);
            if ("添加成功".equals(returnMsg)) {
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put(RETURN_DATA, returnMsg);
            } else if ("修改成功".equals(returnMsg)) {
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put(RETURN_DATA, returnMsg);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap.put(JSON_RESULT, FAILED);
            returnMap = getFailedMap(e.getMessage());
        }
        returnMap.put("eventId", eventVO.getEventId());
        return returnMap;
    }

    /**
     * deleteEvent:删除售后事件
     * 
     * @param resendIds
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteEvent")
    @SystemControllerLog(module = "售后事件管理", operation = "删除售后事件", keyCode = "eventIds")
    public Map<String, Object> deleteEvent(@RequestParam(value = "eventIds") String eventIds) {
        logger.info(String.format("删除售后事件：/afterSale/deleteEvent/%s", eventIds));
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            int result = eventService.deleteAfterSaleEvent(eventIds);
            if (result > 0) {
                returnMap = getSuccessMap("售后事件已删除");
            } else if (0 == result) {
                returnMap = getFailedMap("售后事件[" + eventIds + "]删除失败，请刷新后重试");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap(e.getMessage());
        }
        returnMap.put("eventIds", eventIds);
        return returnMap;
    }

    /**
     * dealEvent：处理售后事件
     * 
     * @param message
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/dealEvent")
    @SystemControllerLog(module = "售后事件管理", operation = "处理售后事件", keyCode = "eventIds")
    public Map<String, Object> dealEvent(@RequestParam(value = "eventIds") String eventIds) {
        logger.info(String.format("处理售后事件：/afterSale/dealEvent/%s", eventIds));
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            int result = eventService.dealEvent(eventIds);
            if (result > 0) {
                returnMap = getSuccessMap("售后事件已处理");
            } else if (0 == result) {
                returnMap = getFailedMap("售后事件[" + eventIds + "]处理失败，请刷新后重试");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap(e.getMessage());
        }
        returnMap.put("eventIds", eventIds);
        return returnMap;
    }

    /**
     * cancelDealEvent：撤销处理售后事件
     * 
     * @param message
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cancelDealEvent")
    @SystemControllerLog(module = "售后事件管理", operation = "撤销处理售后事件", keyCode = "eventIds")
    public Map<String, Object> cancelDealEvent(@RequestParam(value = "eventIds") String eventIds) {
        logger.info(String.format("取消处理售后事件：/afterSale/cancelDealEvent/%s", eventIds));
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            int result = eventService.cancelDealEvent(eventIds);
            if (result > 0) {
                returnMap = getSuccessMap("售后事件已取消处理");
            } else if (0 == result) {
                returnMap = getFailedMap("售后事件[" + eventIds + "]取消处理失败，请刷新后重试");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap(e.getMessage());
        }
        returnMap.put("eventIds", eventIds);
        return returnMap;
    }

    /**
     * completeEvent：完成售后事件
     * 
     * @param message
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/completeEvent")
    @SystemControllerLog(module = "售后事件管理", operation = "完成售后事件", keyCode = "eventIds")
    public Map<String, Object> completeEvent(@RequestParam(value = "eventIds") String eventIds) {
        logger.info(String.format("完成售后事件：/afterSale/completeEvent/%s", eventIds));
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            int result = eventService.completeEvent(eventIds);
            if (result > 0) {
                returnMap = getSuccessMap("售后事件已完成");
            } else if (0 == result) {
                returnMap = getFailedMap("售后事件[" + eventIds + "]完成失败，请刷新后重试");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            returnMap = getFailedMap(e.getMessage());
        }
        returnMap.put("eventIds", eventIds);
        return returnMap;
    }

    private Map<String, Object> getSuccessMap(String message) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put(JSON_RESULT, SUCCESS);
        returnMap.put(JSON_MSG, message);
        return returnMap;
    };

    private Map<String, Object> getFailedMap(String message) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put(JSON_RESULT, FAILED);
        returnMap.put(JSON_MSG, message);
        return returnMap;
    };

    /**
     * 获取系统订单售后事件 create:wangxing 2017-10-20
     *
     * @param orderId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getEventByOrderId")
    public Map<String, Object> getEventByOrderId(String orderId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            List<AfterSaleEventVO> afterSaleEventList = eventService.queryEventListByOrderId(orderId);
            if (afterSaleEventList != null && afterSaleEventList.size() > 0) {
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put(RETURN_DATA, "");
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "获取系统订单售后事件失败");
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        return returnMap;
    }

    /**
     * 获取系统订单对应售后事件列表 wangxing 2017-12-04 add
     *
     * @param orderId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getEventListByOrderId")
    public Map<String, Object> getEventListByOrderId(String orderId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            List<AfterSaleEventVO> afterSaleEventList = eventService.queryEventListByOrderId(orderId);

            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, afterSaleEventList);

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        return returnMap;
    }
}
